<?php
/**
 * @package     Joomla.Platform
 * @subpackage  Form
 *
 * @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 */

defined('JPATH_PLATFORM') or die;

jimport('joomla.html.html');
jimport('joomla.form.formfield');
jimport('joomla.form.helper');
//JFormHelper::loadFieldClass('list');

/**
 * Form Field class for the Joomla Platform.
 * Supports an HTML select list of categories
 *
 * @package     Joomla.Platform
 * @subpackage  Form
 * @since       11.1
 */
class JFormFieldTupleData extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  11.1
	 */
	public $type = 'TupleData';

	/**
	 * Method to get the field options for category
	 * Use the extension attribute in a form to specify the.specific extension for
	 * which categories should be displayed.
	 * Use the show_root attribute to specify whether to show the global category root in the list.
	 *
	 * @return  array    The field option objects.
	 * @since   11.1
	 */
	protected function getInput() {
    $colElements = $this->element->xpath('//column');
    
    if (!$colElements) {
      JError::raiseError('500', 'Column definitions missing');
    }
    if (empty($this->value)) { // Set defaults
      $data = array(array());
      /* @var $def JXMLElement */
      foreach ($colElements as $def) {
        $data[0][$def->getAttribute('name')] = $def->getAttribute('default');
      }
    } else
      $data = $this->value;
    
    $name = $this->name;
    $namesSelectors = array();
    $html = array('<div name="'.$name.'" class="grid" id="albumdata-grid">');
    foreach($data as $i=>$datum) {
      $html[] = '<div class="row">';
      foreach ($colElements as $def) {
        $_type = $def->getAttribute('type');
        $_name = $def->getAttribute('name');
        if ($_type == 'text') {
          $options[] = 'name = "'.$name."[$i][".$_name.']"';
          $options[] = 'value = "'.(is_object($datum)?$datum->$_name:$datum[$_name]).'"';
          $options[] = 'size = "'.$def->getAttribute('size').'"';
          $options[] = 'class = "'.$_name.'"';

          $html[] = '<p><label>'.$def->getAttribute('label').'</label>'
            ."<input type=\"$_type\" ".join(' ', $options)." /></p>"; 
        } else if ($_type == 'textarea') {
          $options[] = 'name = "'.$name."[$i][".$_name.']"';
          $options[] = 'size = "'.$def->getAttribute('size').'"';
          $options[] = 'class = "'.$_name.'"';

          $html[] = '<p><label>'.$def->getAttribute('label').'</label>'
            ."<textarea type=\"$_type\" ".join(' ', $options).'>'.
                (is_object($datum)?$datum->$_name:$datum[$_name])
            .'</textarea></p>'; 
        }
        // for javascript
        $namesSelectors[] = ".$_name"; // for css selector in script
        unset($options);
      }
      $html[] = '<p><a href="#" class="albumdata-grid-remove">Remove</a></p>';
      $html[] = '</div>';
    }
    $html[] = '</div>';
    $html[] = '<div style="clear:both"><a href="#" id="albumdata-grid-add">Add</a></div>';
    
    $nameSelector = join(',',$namesSelectors);    
		$script = <<<EOD
   \n
	window.addEvent('domready', function(){
		var grid = $('albumdata-grid');
    grid.getElements('.albumdata-grid-remove').addEvent('click', function(e){
			e.stop();
			this.getParent('.row').destroy().empty();
			renameRows();
		});
		$('albumdata-grid-add').addEvent('click',function(e){
			e.stop();
			
			var row = grid.getLast('.row');
			var cloned = row.clone();
			cloned.getElements('$nameSelector').set('value','');

			cloned.inject(row,'after');
			renameRows();
			return false;
		});
		
		function renameRows(){
			// Rename row elements
			var rows = $$('.row');
			var rootName = grid.get('name');
			for (var i=0;i<rows.length;i++){
        Array.each(rows[i].getElements('$nameSelector'), function(ele, index){
          ele.set('name',rootName + '[' + i + '][' + ele.get('class') +']');
        });
			}
		}
	});
EOD;
		$style = <<<EOD
   .albumdata-grid-remove, #albumdata-grid-add{float: right}
   .row:only-child .albumdata-grid-remove{display:none}
   .row {float: left; border-bottom:1px solid #ccc; width: 100%}
   #albumdata-grid .row label {padding-left:10px;margin-right: -10px}
EOD;
		
		JFactory::getDocument()->addScriptDeclaration($script);
		JFactory::getDocument()->addStyleDeclaration($style);
		return join("\n", $html);
	}
}
